package com.xw.aspect;

import cn.hutool.cache.impl.TimedCache;
import com.xw.constant.TokenConstant;
import com.xw.enums.ResultEnum;
import com.xw.exception.YdException;
import com.xw.utils.TimedCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description:
 * @Author: y
 * @CreateDate: 7/29/21 10:15 AM
 * @Version: 1.0
 */
@Aspect
@Component
@Slf4j
public class AuthorizeAspect {

    @Pointcut("execution(public * com.xw.controller.admin.*.*(..)) && " +
            "!execution(public * com.xw.controller.admin.*.to*(..))"
    )
    public void verify() {
    }

    @Before("verify()")
    public void doVerify() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        TimedCache<String, String> tokenTimedCache = TimedCacheUtil.TOKEN_TIMED_CACHE;


        assert requestAttributes != null;
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        assert request != null;
        System.out.println("----------------" + request.getRequestURI());


//        if (!request.getRequestURI().contains("release") && !request.getRequestURI().contains("add") && !request.getRequestURI().contains("upd") && !request.getRequestURI().contains("edit") && !request.getRequestURI().contains("del")) {
//            return;
//        }

        //直接返回的路径
//        List<String> list = new ArrayList<>();
//        //模版
//        if (list.contains(request.getRequestURI())) {
//            return;
//        }
        String userId = request.getParameter("userId");
        if (ObjectUtils.isEmpty(userId)) {
            throw new YdException(ResultEnum.FAIL);
        }
//
        String tk = request.getHeader("token");
        String tokenName = String.format(TokenConstant.TOKEN_PREFIX, userId);
        String token = tokenTimedCache.get(tokenName);
//
        if (token == null || tk == null) {
            throw new YdException(ResultEnum.FAIL);
        }
//
        if (!tk.equals(token)) {
            log.error("没有找到用户token");
            throw new YdException(ResultEnum.FAIL);
        }

    }

}